package com.hxl.tech.gateway.auth.model;

import com.hxl.tech.gateway.common.constant.AppConstant;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.ClientDetails;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 应用 Model 
 * @author soliddq
 * @date 2023-09-20
 */
@Entity
@Data
public class Application implements ClientDetails {

    @Id
    private String appId;

    private String appSecret;

    private String appName;

    private String appType;

    private String userId;

    @Enumerated(EnumType.STRING)
    private AppConstant.StateEnum state;

    private String remark;

    private String createBy;

    private LocalDateTime createTime;

    private String redirectUri; // 重定向定制，必须和授权链接一致

    private String receiveTokenUri; // 接受Token地址

    @Transient
    private String grantTypes = "authorization_code,refresh_token"; // Oauth支持模式

    @Transient
    private Integer accessTokenValiditySeconds = 3600 * 24; // Access Token过期时间 1天

    @Transient
    private Integer refreshTokenValiditySeconds = 3600 * 24 * 10; // Refresh Token过期时间 10天

    @Transient
    private boolean autoApprove = true;

    @Transient
    private String additionalInformation;

    @Transient
    private String resourceId;

    @Override
    public String getClientId() {
        return appId;
    }

    @Override
    public String getClientSecret() { return appSecret; }

    @Override
    public Set<String> getResourceIds() {
        return Collections.singleton(resourceId);
    }

    @Override
    public boolean isSecretRequired() {
        return true;
    }

    @Override
    public boolean isScoped() {
        return false;
    }

    @Override
    public Set<String> getScope() {
        return Collections.singleton("read");
    }

    @Override
    public boolean isAutoApprove(String scope) {
        return autoApprove;
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return Arrays.stream(grantTypes.split(",")).collect(Collectors.toSet());
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return Collections.singleton(redirectUri);
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        return Collections.emptyMap();
    }

}
